// src/composables/useEditPile.js

import {ref, reactive} from 'vue';
import axios from 'axios';
import {ElMessage} from 'element-plus';

export function useEditPile() {
    // 编辑/查看弹窗
    const editDialogVisible = ref(false);
    const viewDialogVisible = ref(false);

    // 编辑表单
    const editForm = reactive({
        id: null,
        pileName: "", // pile_name
        pileCode: "", // pile_code
        pileType: "", // pile_type
        pilePower: null, // pile_power
        pileModel: "", // pile_model
        pileDesc: "", // pile_desc
        suitableVehicle: "", // suitable_vehicle
        pileStatus: "空闲中", // 默认空闲
        stationId: null, // station_id
        pileImgUrl: "", // pile_img_url
        chargingGunCount: 0,
        chargingGuns: [],
    });

    // 查看表单
    const viewForm = reactive({
        chargingPile: {
            id: null,
            pileName: "", // pile_name
            pileCode: "", // pile_code
            pileType: "", // pile_type
            pilePower: null, // pile_power
            pileModel: "", // pile_model
            pileDesc: "", // pile_desc
            suitableVehicle: "", // suitable_vehicle
            pileStatus: "空闲中", // 默认空闲
            stationId: null, // station_id
            pileImgUrl: "", // pile_img_url
            chargingGunCount: 0,
        },
        chargingGuns: [],
    });

    // 打开编辑弹窗
    const editPile = async (row) => {
        try {
            const response = await axios.get(`/chargingPile/getChargingPileWithChargingGun/${row.id}`);
            const {chargingPile, chargingGuns} = response.data;
            Object.assign(editForm, chargingPile);
            editForm.chargingGuns = chargingGuns;
            editDialogVisible.value = true;
        } catch (error) {
            console.error('加载站点数据失败', error);
            ElMessage.error('加载站点数据失败');
        }
    };

    // 打开查看弹窗
    const viewPile = async (row) => {
        try {
            const res = await axios.get(`/chargingPile/getChargingPileWithChargingGun/${row.id}`);
            // 打印解析后的 chargingPile 和 chargingGuns 数据
            console.log('解析的 res.data 数据:', res.data);
            console.log('解析的 chargingPile 数据:', res.data.chargingPile);
            console.log('解析的 chargingGuns 数据:', res.data.chargingGuns);
            const {chargingPile, chargingGuns} = res.data;
            Object.assign(viewForm, chargingPile);
            viewForm.chargingGuns = chargingGuns;

            viewDialogVisible.value = true;
        } catch (error) {
            console.error('查看站点失败', error);
            ElMessage.error('查看站点失败');
        }
    };

    return {
        editDialogVisible,
        viewDialogVisible,
        editForm,
        viewForm,
        editPile,
        viewPile,
    };
}
